package com.longkier.gx_library_springboot.Service;

import com.longkier.gx_library_springboot.entity.Book;
import com.longkier.gx_library_springboot.entity.HomeRole;
import com.longkier.gx_library_springboot.repository.BookRepository;
import com.longkier.gx_library_springboot.repository.HomeRepository;
import com.longkier.gx_library_springboot.utils.FileUploadUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class HomeService {
    private final BookRepository bookRepository;
    private final HomeRepository homeRepository;

    // 根据首页规则获取最新书籍
    public List<Book> homeGetLatestBooks() {
        Optional<HomeRole> optionalHomeRole = homeRepository.findById(1L);
        int netBookSize = 0;
        if (optionalHomeRole.isPresent()) {
            HomeRole homeRole = optionalHomeRole.get();
            netBookSize = homeRole.getHomeBookNewNumber();
        }
        return bookRepository.homeFindTopBooksByLatestUpdate(Pageable.ofSize(netBookSize));
    }

    // 根据首页规则获取随机书籍
    public List<Book> homeGetRandomBooks() {
        Optional<HomeRole> optionalHomeRole = homeRepository.findById(1L);
        int netBookSize = 0;
        if (optionalHomeRole.isPresent()) {
            HomeRole homeRole = optionalHomeRole.get();
            netBookSize = homeRole.getHomeBookRandomNumber();
        }
        return bookRepository.homeFindRandomBooks(netBookSize);
    }

    // 获取首页管理规则
    public Optional<HomeRole> getHomeRole(Long id) {
        return homeRepository.findById(id);
    }

    // 新增或更新首页管理规则
    public HomeRole saveOrUpdateHomeRole(HomeRole homeRole) {
        Optional<HomeRole> optionalHomeRole = homeRepository.findById(1L);
        if (optionalHomeRole.isPresent()) { //回写首页轮播图
            HomeRole homeRoleFromDB = optionalHomeRole.get();
            homeRole.setHomeCarousel1(homeRoleFromDB.getHomeCarousel1());
            homeRole.setHomeCarousel2(homeRoleFromDB.getHomeCarousel2());
            homeRole.setHomeCarousel3(homeRoleFromDB.getHomeCarousel3());
        }
        homeRole.setHomeRoleId(1L);
        return homeRepository.save(homeRole);
    }

    /**
     * 保存轮播图并更新首页规则
     *
     * @param file          上传的文件
     * @param carouselIndex 轮播图索引 (1-3)
     * @param homeRoleId    首页规则ID
     * @throws IOException 文件保存异常
     */
    public void saveCarouselImage(MultipartFile file, int carouselIndex, Long homeRoleId) throws IOException {
        // 获取指定的 HomeRole 实例
        Optional<HomeRole> optionalHomeRole = homeRepository.findById(homeRoleId);
        if (optionalHomeRole.isEmpty()) {
            throw new IllegalArgumentException("未找到指定的首页管理规则");
        }
        HomeRole homeRole = optionalHomeRole.get();
        // 获取旧的轮播图文件路径
        String oldFilePath = switch (carouselIndex) {
            case 1 -> homeRole.getHomeCarousel1();
            case 2 -> homeRole.getHomeCarousel2();
            case 3 -> homeRole.getHomeCarousel3();
            default -> throw new IllegalArgumentException("无效的轮播图索引");
        };
        // 如果存在旧文件，则删除旧文件
        if (oldFilePath != null) {FileUploadUtils.deleteFile(oldFilePath);}
        // 保存文件
        String filePath = FileUploadUtils.saveFile(file, "carousel_" + carouselIndex + "_" + homeRoleId);
        // 更新 HomeRole 对象对应的字段
        switch (carouselIndex) {
            case 1:
                homeRole.setHomeCarousel1(filePath);
                break;
            case 2:
                homeRole.setHomeCarousel2(filePath);
                break;
            case 3:
                homeRole.setHomeCarousel3(filePath);
                break;
        }
        // 保存更新后的 HomeRole 对象
        homeRepository.save(homeRole);
    }
}
